package com.neuedu.mvc.controller;

import com.neuedu.mvc.entity.User;
import com.neuedu.mvc.service.IUserService;
import com.neuedu.mvc.valid.ValiditionUserName;
import com.neuedu.mvc.vo.ParamVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目：      spring-framework
 * 类名:       UserController
 * 创建时间：  2024/3/18 16：23
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;


    /**
     * http://localhost:8080/web/user/list
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
//    @RequestMapping("/list")
//    public ModelAndView list(HttpServletRequest request, HttpServletResponse response, HttpSession session ) throws ServletException, IOException {
//        ServletContext app1 = session.getServletContext();
//        ServletContext app2 = request.getServletContext();
//        System.out.println("app = " + app1);
//
//        ModelAndView mv = new ModelAndView();
//        mv.addObject("userList",userService.selectListEntity());
//        mv.setViewName("/user/user_list");
//        return mv;
//    }


    @RequestMapping("/list")
    public String list(ModelMap model , HttpServletRequest request, HttpServletResponse response, HttpSession session ) throws ServletException, IOException {
        ServletContext app1 = session.getServletContext();
        ServletContext app2 = request.getServletContext();
        System.out.println("app = " + app1);

        model.addAttribute("userList",userService.selectListEntity());
        return "/user/user_list";
    }


//    @RequestMapping("toAdd")
//    public ModelAndView  toAdd(){
//        ModelAndView mv = new ModelAndView();
//        mv.setViewName("/user/user_add");
//        return mv;
//    }

    @RequestMapping("toAdd")
    public String  toAdd(){
        return "/user/user_add";
    }

    /**
     * http://lo
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @RequestMapping("add")
    public String  add(HttpServletRequest request,HttpServletResponse response) throws ParseException {

        // 获取参数
        String userId = request.getParameter("userId");
        String userName = request.getParameter("userName");
        String birthday = request.getParameter("birthday");// "2024-03-19"  "asdfasfasdfas"
        String gender = request.getParameter("gender");
        String status = request.getParameter("status");
        //调用service保存

        User user = new User();
        user.setUserId(Integer.parseInt(userId));
        user.setUserName(userName);
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        user.setGender(gender);
        user.setStatus(Integer.parseInt(status));
        boolean success = userService.insert(user);
       String path = "";
        if(success) {
//            重定向
//            redirect   和  forward  使用的不带前缀和后缀的视图层处理
            path = "redirect:/user/list";
        }else{
            path = "/user/user_add";
        }
        return path;
    }

    @RequestMapping("forward")
    public ModelAndView  forward(HttpServletRequest request) throws ParseException {
        ModelAndView mv = new ModelAndView();

//        mv.setViewName("/dept/dept_add.jsp");
        mv.setViewName("forward:/dept/dept_add.jsp");
        return mv;

    }


    /**
     * http://localhost:8080/web/user/toEdit?userId=>>>
     * @param modelMap
     * @param userId
     * @return
     */
    @GetMapping("/toEdit")
    public String toEdit(  ModelMap modelMap,      Integer userId  ){
        modelMap.addAttribute("user",userService.selectById(userId));
        return "/user/user_edit";
    }

    @GetMapping("/toEdit2")
    public String toEdit2(  ModelMap modelMap,      Integer userId  ){
        modelMap.addAttribute("user",userService.selectById(userId));
        return "/user/user_edit2";
    }


//    @RequestMapping(value = "update")
////    public String  update(   String userId,   String userName,  String birthday,   String gender,  String status  ) throws ParseException {
//    public String  update( User user , @RequestParam(value = "test",required = false,defaultValue = "123456") String myVar ) throws ParseException {
//
//        System.out.println("myVar = " + myVar);
//
//
//        //调用service保存
//        boolean success = userService.updateById(user);
//        String path = "";
//        if(success) {
////            重定向
////            redirect   和  forward  使用的不带前缀和后缀的视图层处理
//            path = "redirect:/user/list";
//        }else{
//            path = "/user/user_edit";
//        }
//        return path;
//    }



    @RequestMapping(value = "update")
    public String  update(@ModelAttribute("user") @Validated  User user  , BindingResult result , Model model    ) throws ParseException {

        //有字段不满足校验规则
        if(result.getErrorCount()>0){
            Map errs = new HashMap();
            for (FieldError fieldError : result.getFieldErrors()) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                errs.put(field,defaultMessage);  //status  xzzzzzz
            }
            model.addAttribute("errs",errs);
            return "/user/user_edit";
        }




        //调用service保存
        boolean success = userService.updateById(user);
        String path = "";
        if(success) {
            path = "redirect:/user/list";
        }else{
            path = "/user/user_edit";
        }
        return path;
    }

    @RequestMapping(value = "update2")
    public String  update2(@Validated(value = ValiditionUserName.class ) User user  , BindingResult result , Model model    ) throws ParseException {

        //有字段不满足校验规则
        if(result.getErrorCount()>0){
            Map errs = new HashMap();
            for (FieldError fieldError : result.getFieldErrors()) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                errs.put(field,defaultMessage);  //status  xzzzzzz
            }
            model.addAttribute("errs",errs);
            return "/user/user_edit2";
        }




        //调用service保存
        boolean success = userService.updateById(user);
        String path = "";
        if(success) {
            path = "redirect:/user/list";
        }else{
            path = "/user/user_edit";
        }
        return path;
    }




    @RequestMapping("batchDel")
    public String batchDel(int[] ids){
        for (int id : ids) {
            userService.deleteById(id);
        }

        return "redirect:/user/list";
    }


    /**
     *    http://ssxxxx/web/user/batchAdd?userList[0].userId=1
     *       new User(1)---list  0
     *    http://ssxxxx/web/user/batchAdd?userList[1].userId=2
     *      new User(2)---list  1
     *    http://ssxxxx/web/user/batchAdd?userList[2].userId=3
     *      new User(3)---list  0
     *
     *
     * list{
     *
     *     new User(1)
     *      new User(2)
     *      new User(3)
     * }
     *
     *
     *
     *
     *
     * @param vo
     * @return
     */
    @RequestMapping("batchAdd")
    public String batchAdd(ParamVo vo ){

        for (User user : vo.getUserList()) {
            userService.insert(user);
        }

        return "redirect:/user/list";
    }

    /**
     * 跳转到批量添加页面
     * @param vo
     * @return
     */
    @RequestMapping("toBatchAdd")
    public String toBatchAdd(ParamVo vo ){
        return "/user/user_add_batch";
    }



    @RequestMapping("toAdd2")
    public String  toAdd2(){
        return "/user/user_add2";
    }
    @RequestMapping("add2")
    public String  add(@RequestParam Map map) throws ParseException {

        System.out.println("map = " + map);
        //没有真正插入数据库，页面没有变化


        return "redirect:/user/list";
    }

}
